package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket=null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //.客户端在new Socket的时候，就会和服务器建立起TCP连接
        socket=new Socket(serverIp, serverPort);
    }
    public void start() throws IOException {
        System.out.println("client start!");

        try (InputStream inputStream=socket.getInputStream();
             OutputStream outputStream=socket.getOutputStream()){
            Scanner scanner=new Scanner(System.in);
            Scanner scannerNetwork=new Scanner(inputStream);
            PrintWriter writer=new PrintWriter(outputStream);

            while(true){
                //1.从控制台读取用户输入
                System.out.printf("->");
                String request= scanner.next();
                //2.把请求发送给服务器
                writer.println(request);
                writer.flush();
                //3.读取服务器的响应
                String response=scannerNetwork.next();
                //4.打印响应
                System.out.println(response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
         finally {
            try {
                socket.close();
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient=new TcpEchoClient("192.168.160.64",10009);
        tcpEchoClient.start();
    }
}
